/**
 * 军棋游戏主类
 * 基于原网页版军棋游戏逻辑，适配微信小游戏Canvas API
 */
export default class JunqiGame {
  constructor() {
    // 获取Canvas上下文
    this.ctx = GameGlobal.canvas.getContext('2d');
    this.canvas = GameGlobal.canvas;

    // 获取屏幕尺寸信息
    const windowInfo = wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync();
    this.screenWidth = windowInfo.screenWidth;
    this.screenHeight = windowInfo.screenHeight;

    // 棋盘基本参数
    this.boardWidth = 5;
    this.boardHeight = 12;

    // 自适应计算
    this.calculateAdaptiveLayout();

    // 游戏状态
    this.gamePhase = 'setup'; // 'setup' = 布阵阶段, 'battle' = 对战阶段
    this.currentPlayer = '0'; // '0'=红方, '1'=黑方
    this.selectedPiece = null;
    this.gameOver = false;

    // 布阵状态
    this.setupComplete = { '0': false, '1': false };

    // 大本营位置（选择左右两侧的两个安全位置）
    this.baseCamps = {
      '0': [[1, 11], [3, 11]], // 红方大本营
      '1': [[1, 0], [3, 0]]    // 黑方大本营
    };

    // 初始化棋盘
    this.initBoard();

    // 绑定触摸事件
    this.bindEvents();

    // 调试模式：在控制台输出坐标信息
    if (typeof console !== 'undefined') {
      console.log('军棋游戏初始化完成');
      console.log(`屏幕尺寸: ${this.screenWidth}x${this.screenHeight}`);
      console.log(`游戏区域: ${this.gameWidth}x${this.gameHeight}`);
      console.log(`格子尺寸: ${this.cellWidth}x${this.cellHeight}`);
      console.log(`偏移量: (${this.offsetX}, ${this.offsetY})`);
      this.debugCoordinateSystem();
    }
  }

  // 自适应布局计算
  calculateAdaptiveLayout() {
    console.log(`开始计算布局，屏幕尺寸: ${this.screenWidth}x${this.screenHeight}`);

    // 大幅减少边距，最大化棋盘空间
    const topMargin = Math.max(10, this.screenHeight * 0.01);  // 最小10px，或1%顶部空间
    const bottomMargin = Math.max(60, this.screenHeight * 0.04); // 最小60px，或4%底部空间
    const availableHeight = this.screenHeight - topMargin - bottomMargin;

    // 极小的左右边距
    const horizontalMargin = Math.max(5, this.screenWidth * 0.01); // 最小5px，或1%左右边距
    const availableWidth = this.screenWidth - horizontalMargin * 2;

    console.log(`可用空间: ${availableWidth}x${availableHeight}`);

    // 计算格子尺寸 - 优先考虑屏幕利用率
    let cellWidth, cellHeight;
    let cellWidth2, cellHeight2;

    // 方法1：基于可用高度计算格子大小
    cellHeight = availableHeight / this.boardHeight;
    cellWidth = cellHeight * (120 / 90); // 保持原始4:3宽高比

    const method1Width = cellWidth * this.boardWidth;
    const method1Height = cellHeight * this.boardHeight;
    console.log(`方法1 - 基于高度计算: 格子${cellWidth.toFixed(1)}x${cellHeight.toFixed(1)}, 总宽度${method1Width.toFixed(1)}, 总高度${method1Height.toFixed(1)}`);

    // 方法2：基于可用宽度计算格子大小
    cellWidth2 = availableWidth / this.boardWidth;
    cellHeight2 = cellWidth2 * (90 / 120); // 保持原始宽高比

    const method2Height = cellHeight2 * this.boardHeight;
    const method2Width = cellWidth2 * this.boardWidth;
    console.log(`方法2 - 基于宽度计算: 格子${cellWidth2.toFixed(1)}x${cellHeight2.toFixed(1)}, 总宽度${method2Width.toFixed(1)}, 总高度${method2Height.toFixed(1)}`);

    // 检查方法1是否超出屏幕限制
    const method1FitsWidth = method1Width <= availableWidth;
    const method1FitsHeight = method1Height <= availableHeight;
    const method1Valid = method1FitsWidth && method1FitsHeight;

    console.log(`方法1屏幕适配: 宽度${method1FitsWidth ? '✅' : '❌'}, 高度${method1FitsHeight ? '✅' : '❌'}, 总体${method1Valid ? '✅' : '❌'}`);

    // 检查方法2是否超出屏幕限制
    const method2FitsWidth = method2Width <= availableWidth;
    const method2FitsHeight = method2Height <= availableHeight;
    const method2Valid = method2FitsWidth && method2FitsHeight;

    console.log(`方法2屏幕适配: 宽度${method2FitsWidth ? '✅' : '❌'}, 高度${method2FitsHeight ? '✅' : '❌'}, 总体${method2Valid ? '✅' : '❌'}`);

    // 选择方法：优先选择有效的方法，然后选择格子更大的方法
    if (method1Valid && method2Valid) {
      // 两个方法都有效，选择格子更大的
      if (cellHeight >= cellHeight2) {
        cellWidth = cellWidth;
        cellHeight = cellHeight;
        console.log(`选择方法1（基于高度）- 两个都有效，格子更大`);
      } else {
        cellWidth = cellWidth2;
        cellHeight = cellHeight2;
        console.log(`选择方法2（基于宽度）- 两个都有效，格子更大`);
      }
    } else if (method1Valid) {
      // 只有方法1有效
      cellWidth = cellWidth;
      cellHeight = cellHeight;
      console.log(`选择方法1（基于高度）- 只有此方法有效`);
    } else if (method2Valid) {
      // 只有方法2有效
      cellWidth = cellWidth2;
      cellHeight = cellHeight2;
      console.log(`选择方法2（基于宽度）- 只有此方法有效`);
    } else {
      // 两个方法都无效，强制使用基于宽度的方法（确保能显示）
      cellWidth = cellWidth2;
      cellHeight = cellHeight2;
      console.log(`强制选择方法2（基于宽度）- 两个方法都超出屏幕，选择基于宽度确保显示`);
    }

    // 确保最小格子尺寸 - 增大最小尺寸要求
    const minCellSize = Math.min(this.screenWidth, this.screenHeight) * 0.08; // 提高到8%
    console.log(`最小格子尺寸要求: ${minCellSize.toFixed(1)}`);

    if (cellWidth < minCellSize) {
      console.log(`格子尺寸过小，强制调整到最小尺寸`);
      cellWidth = minCellSize;
      cellHeight = minCellSize * 0.75;
    }

    // 设置实际尺寸
    this.cellWidth = cellWidth;
    this.cellHeight = cellHeight;
    this.gameWidth = cellWidth * this.boardWidth;
    this.gameHeight = cellHeight * this.boardHeight;

    // 计算居中偏移 - 确保棋盘完全居中
    this.offsetX = (this.screenWidth - this.gameWidth) / 2;

    // 垂直居中，但要为UI预留空间
    const totalRequiredHeight = this.gameHeight + 100; // 棋盘高度 + UI空间
    const availableVerticalSpace = this.screenHeight;

    if (totalRequiredHeight <= availableVerticalSpace) {
      // 如果总高度不超过屏幕，则垂直居中
      this.offsetY = (availableVerticalSpace - totalRequiredHeight) / 2;
    } else {
      // 如果太高，则使用最小顶部边距
      this.offsetY = topMargin;
    }

    // 确保偏移量不为负数
    this.offsetX = Math.max(0, this.offsetX);
    this.offsetY = Math.max(0, this.offsetY);

    // 缩放比例（用于UI元素）
    this.scale = Math.min(this.cellWidth / 120, this.cellHeight / 90);

    // 优化UI区域参数
    const uiSpacing = Math.max(10, this.screenHeight * 0.015); // 减少UI间距
    this.uiTopY = this.offsetY + this.gameHeight + uiSpacing;
    this.buttonY = this.uiTopY + Math.max(30, this.screenHeight * 0.035);

    console.log(`最终布局: 格子${cellWidth.toFixed(1)}x${cellHeight.toFixed(1)}, 游戏区域${this.gameWidth.toFixed(1)}x${this.gameHeight.toFixed(1)}`);
    console.log(`居中偏移: X=${this.offsetX.toFixed(1)}, Y=${this.offsetY.toFixed(1)}`);
    console.log(`棋盘边界: 左${this.offsetX.toFixed(1)}, 右${(this.offsetX + this.gameWidth).toFixed(1)}, 上${this.offsetY.toFixed(1)}, 下${(this.offsetY + this.gameHeight).toFixed(1)}`);
    console.log(`屏幕利用率: 宽度${(this.gameWidth/this.screenWidth*100).toFixed(1)}%, 高度${(this.gameHeight/this.screenHeight*100).toFixed(1)}%`);
  }

  // 调试坐标系统
  debugCoordinateSystem() {
    console.log('\n=== 自适应坐标系统调试信息 ===');

    // 屏幕信息
    console.log(`屏幕尺寸: ${this.screenWidth}x${this.screenHeight}`);
    console.log(`屏幕比例: ${(this.screenWidth / this.screenHeight).toFixed(3)}`);

    // 格子尺寸检查
    const targetCellSize = Math.min(this.screenWidth, this.screenHeight) * 0.08;
    console.log(`目标格子尺寸: ${targetCellSize.toFixed(1)}px (屏幕短边的8%)`);
    console.log(`实际格子尺寸: ${this.cellWidth.toFixed(1)}x${this.cellHeight.toFixed(1)}px`);
    console.log(`格子尺寸是否达标: ${this.cellWidth >= targetCellSize ? '✅ 是' : '❌ 否'}`);

    // 布局信息
    console.log('\n布局信息:');
    console.log(`游戏区域: ${Math.round(this.gameWidth)}x${Math.round(this.gameHeight)}`);
    console.log(`游戏占用屏幕: 宽度${(this.gameWidth / this.screenWidth * 100).toFixed(1)}%, 高度${(this.gameHeight / this.screenHeight * 100).toFixed(1)}%`);
    console.log(`缩放比例: ${this.scale.toFixed(3)} (基于原始120x90像素)`);
    console.log(`偏移量: (${Math.round(this.offsetX)}, ${Math.round(this.offsetY)})`);

    // 可视化检查
    console.log('\n可视化检查:');
    console.log(`棋盘左上角: (${Math.round(this.offsetX)}, ${Math.round(this.offsetY)})`);
    console.log(`棋盘右下角: (${Math.round(this.offsetX + this.gameWidth)}, ${Math.round(this.offsetY + this.gameHeight)})`);
    console.log(`棋盘是否在屏幕内: ${this.offsetX >= 0 && this.offsetY >= 0 &&
             this.offsetX + this.gameWidth <= this.screenWidth &&
             this.offsetY + this.gameHeight <= this.screenHeight ? '✅ 是' : '❌ 否'}`);

    // 居中检查
    console.log('\n居中检查:');
    const centerX = this.offsetX + this.gameWidth / 2;
    const centerY = this.offsetY + this.gameHeight / 2;
    const screenCenterX = this.screenWidth / 2;
    const screenCenterY = this.screenHeight / 2;

    console.log(`棋盘中心: (${Math.round(centerX)}, ${Math.round(centerY)})`);
    console.log(`屏幕中心: (${Math.round(screenCenterX)}, ${Math.round(screenCenterY)})`);
    console.log(`水平居中偏差: ${Math.abs(centerX - screenCenterX).toFixed(1)}px`);
    console.log(`垂直居中偏差: ${Math.abs(centerY - screenCenterY).toFixed(1)}px`);
    console.log(`是否水平居中: ${Math.abs(centerX - screenCenterX) < 5 ? '✅ 是' : '❌ 否'}`);
    console.log(`是否垂直居中: ${Math.abs(centerY - screenCenterY) < 10 ? '✅ 是' : '❌ 否'}`);

    // 重新计算偏移以确保绝对居中
    const perfectOffsetX = Math.max(0, (this.screenWidth - this.gameWidth) / 2);
    const perfectOffsetY = Math.max(0, (this.screenHeight - this.gameHeight - 100) / 2); // 为UI预留100px

    console.log('\n偏移修正检查:');
    console.log(`当前偏移: X=${this.offsetX.toFixed(1)}, Y=${this.offsetY.toFixed(1)}`);
    console.log(`完美偏移: X=${perfectOffsetX.toFixed(1)}, Y=${perfectOffsetY.toFixed(1)}`);
    console.log(`偏移是否需要修正: ${Math.abs(this.offsetX - perfectOffsetX) > 1 || Math.abs(this.offsetY - perfectOffsetY) > 1 ? '❌ 是' : '✅ 否'}`);

    // 如果偏移不准确，强制修正
    if (Math.abs(this.offsetX - perfectOffsetX) > 1 || Math.abs(this.offsetY - perfectOffsetY) > 1) {
      console.log('强制修正偏移以确保完美居中...');
      this.offsetX = perfectOffsetX;
      this.offsetY = perfectOffsetY;

      // 重新计算UI位置
      const uiSpacing = Math.max(10, this.screenHeight * 0.015);
      this.uiTopY = this.offsetY + this.gameHeight + uiSpacing;
      this.buttonY = this.uiTopY + Math.max(30, this.screenHeight * 0.035);

      console.log(`修正后偏移: X=${this.offsetX.toFixed(1)}, Y=${this.offsetY.toFixed(1)}`);
      console.log(`修正后UI位置: Y=${this.uiTopY.toFixed(1)}, 按钮=${this.buttonY.toFixed(1)}`);
    }

    // UI信息
    console.log('\nUI布局:');
    console.log(`UI区域Y坐标: ${Math.round(this.uiTopY)}`);
    console.log(`按钮Y坐标: ${Math.round(this.buttonY)}`);
    console.log(`UI距离底部: ${Math.round(this.screenHeight - this.buttonY)}px`);

    // 测试几个关键位置
    const testPositions = [
      { x: 0, y: 0, desc: '左上角' },
      { x: 2, y: 5, desc: '中心区域' },
      { x: 4, y: 11, desc: '右下角' }
    ];

    console.log('\n关键位置坐标:');
    testPositions.forEach(pos => {
      const isCircle = this.list_circle.some(circle => circle[0] === pos.x && circle[1] === pos.y);
      const canvasPos = this.toCanvas(pos.x, pos.y, isCircle);
      console.log(`${pos.desc}: 游戏坐标(${pos.x},${pos.y}) [${isCircle ? '圆形' : '方形'}] -> Canvas坐标(${Math.round(canvasPos.x)},${Math.round(canvasPos.y)})`);
    });

    // 格子大小对比
    console.log('\n格子大小分析:');
    console.log(`每个格子相当于屏幕: 宽度${(this.cellWidth/this.screenWidth*100).toFixed(1)}%, 高度${(this.cellHeight/this.screenHeight*100).toFixed(1)}%`);

    // 显示大本营位置
    console.log('\n大本营位置:');
    Object.entries(this.baseCamps).forEach(([playerId, positions]) => {
      console.log(`${playerId === '0' ? '红方' : '黑方'}:`, positions);
    });
  }

  initBoard() {
    // 棋子等级定义
    this.pieceRanks = {
      '司令': 8, '军长': 7, '师长': 6, '旅长': 5, '团长': 4,
      '营长': 3, '连长': 2, '排长': 1, '工兵': 0,
      '地雷': 9, '炸弹': 10, '军旗': 11
    };

    // 特殊位置定义
    this.list_circle = [
      [1, 2], [3, 2], [2, 3], [1, 4], [3, 4],
      [1, 7], [3, 7], [2, 8], [1, 9], [3, 9]
    ];

    this.list_fast = [
      [0, 1], [1, 1], [2, 1], [3, 1], [4, 1], [0, 2], [4, 2],
      [0, 3], [4, 3], [0, 4], [4, 4], [0, 5], [1, 5], [2, 5], [3, 5], [4, 5],
      [0, 6], [1, 6], [2, 6], [3, 6], [4, 6], [0, 7], [4, 7],
      [0, 8], [4, 8], [0, 9], [4, 9], [0, 10], [1, 10], [2, 10], [3, 10], [4, 10]
    ];

    this.list_block = [
      [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10], [0, 11],
      [1, 0], [1, 1], [1, 3], [1, 5], [1, 6], [1, 8], [1, 10], [1, 11],
      [2, 0], [2, 1], [2, 2], [2, 4], [2, 5], [2, 6], [2, 7], [2, 9], [2, 10], [2, 11],
      [3, 0], [3, 1], [3, 3], [3, 5], [3, 6], [3, 8], [3, 10], [3, 11],
      [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [4, 11]
    ];

    // 初始化棋盘状态
    this.board = {};
    this.initPieces();
  }

  initPieces() {
    // 定义双方棋子
    this.playerPieces = {
      '0': [ // 红方棋子
        '军旗', '司令', '军长', '师长', '师长', '旅长', '旅长', '团长', '团长',
        '营长', '营长', '连长', '连长', '连长', '工兵', '工兵', '工兵', '排长',
        '排长', '排长', '地雷', '地雷', '地雷', '炸弹', '炸弹'
      ],
      '1': [ // 黑方棋子
        '军旗', '司令', '军长', '师长', '师长', '旅长', '旅长', '团长', '团长',
        '营长', '营长', '连长', '连长', '连长', '工兵', '工兵', '工兵', '排长',
        '排长', '排长', '地雷', '地雷', '地雷', '炸弹', '炸弹'
      ]
    };

    // 初始化棋盘为空
    for (let x = 0; x < 5; x++) {
      for (let y = 0; y < 12; y++) {
        const key = `${x},${y}`;
        this.board[key] = null;
      }
    }

    // 生成随机初始布局
    this.generateRandomSetup();
  }

  generateRandomSetup() {
    // 为双方生成随机布局
    ['0', '1'].forEach(playerId => {
      const pieces = [...this.playerPieces[playerId]];
      const shuffledPieces = this.shuffle(pieces);

      // 获取己方半区的有效位置
      const validPositions = [];
      for (let x = 0; x < 5; x++) {
        for (let y = 0; y < 6; y++) {
          const actualY = playerId === '0' ? y + 6 : y;
          if (this.list_block.some(blockPos => blockPos[0] === x && blockPos[1] === actualY)) {
            validPositions.push([x, actualY]);
          }
        }
      }

      // 随机放置棋子
      shuffledPieces.forEach((pieceType, index) => {
        if (index < validPositions.length) {
          const [x, y] = validPositions[index];
          const key = `${x},${y}`;

          this.board[key] = {
            colorId: playerId,
            type: pieceType,
            rank: this.pieceRanks[pieceType],
            revealed: playerId === this.currentPlayer
          };
        }
      });
    });
  }

  shuffle(array) {
    const shuffled = [...array];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
  }

  bindEvents() {
    // 微信小游戏触摸事件
    wx.onTouchStart((e) => {
      const touch = e.touches[0];
      this.handleClick(touch.clientX, touch.clientY);
    });

    // 添加按钮区域触摸事件
    wx.onTouchStart((e) => {
      const touch = e.touches[0];
      this.handleButtonTouch(touch.clientX, touch.clientY);
    });
  }

  handleClick(x, y) {
    if (this.gameOver) return;

    // 转换为游戏坐标（考虑偏移）
    const gameX = Math.floor((x - this.offsetX) / this.cellWidth);
    const gameY = Math.floor((y - this.offsetY) / this.cellHeight);
    const key = `${gameX},${gameY}`;

    // 检查是否是有效位置
    if (!this.list_block.some(pos => pos[0] === gameX && pos[1] === gameY)) {
      return;
    }

    const piece = this.board[key];

    if (this.gamePhase === 'setup') {
      this.handleSetupPhaseClick(gameX, gameY, piece);
    } else {
      this.handleBattlePhaseClick(gameX, gameY, piece);
    }
  }

  handleButtonTouch(x, y) {
    // 按钮区域检查（使用自适应坐标）
    const buttonWidth = this.gameWidth * 0.26; // 按钮宽度为游戏宽度的26%
    const buttonHeight = this.screenHeight * 0.05; // 按钮高度为屏幕高度的5%
    const buttonX = this.screenWidth / 2 - buttonWidth / 2;

    // 检查是否点击了按钮区域
    if (y >= this.buttonY && y <= this.buttonY + buttonHeight &&
        x >= buttonX && x <= buttonX + buttonWidth) {
      if (this.gamePhase === 'setup') {
        this.completeSetup();
      } else {
        this.restart();
      }
    }
  }

  toGameCoords(canvasX, canvasY) {
    // 使用自适应格子尺寸：(x, y) = (canvasX//cellWidth, canvasY//cellHeight)
    return {
      x: Math.floor(canvasX / this.cellWidth),
      y: Math.floor(canvasY / this.cellHeight)
    };
  }

  toCanvas(x, y, isCircle = false) {
    // 自适应坐标转换
    let canvasX, canvasY;

    if (isCircle) {
      // 圆形位置：格子中心
      canvasX = this.offsetX + x * this.cellWidth + this.cellWidth / 2;
      canvasY = this.offsetY + y * this.cellHeight + this.cellHeight / 2;
    } else {
      // 方形位置：格子左上角
      canvasX = this.offsetX + x * this.cellWidth;
      canvasY = this.offsetY + y * this.cellHeight;
    }

    return { x: canvasX, y: canvasY };
  }

  handleSetupPhaseClick(x, y, piece) {
    const isPlayerArea = this.isInPlayerArea(x, y, this.currentPlayer);
    if (!isPlayerArea) return;

    if (this.selectedPiece) {
      if (!piece || piece.colorId === this.currentPlayer) {
        if (this.isValidSetupPosition(this.selectedPiece, x, y)) {
          this.movePieceInSetup(this.selectedPiece, x, y);
          this.selectedPiece = null;
        }
      }
    } else {
      if (piece && piece.colorId === this.currentPlayer) {
        this.selectedPiece = { x, y };
      }
    }
  }

  handleBattlePhaseClick(x, y, piece) {
    if (this.selectedPiece) {
      if (!piece) {
        if (this.isValidMove(this.selectedPiece, x, y)) {
          this.movePiece(this.selectedPiece, x, y);
          this.selectedPiece = null;
          this.switchTurn();
        }
      } else if (piece.colorId === this.currentPlayer) {
        if (this.canMove(piece)) {
          this.selectedPiece = { x, y };
        }
      } else {
        if (this.isValidMove(this.selectedPiece, x, y)) {
          this.autoBattle(this.selectedPiece, x, y);
          this.selectedPiece = null;
          this.switchTurn();
        }
      }
    } else {
      if (piece && piece.colorId === this.currentPlayer) {
        if (this.canMove(piece)) {
          this.selectedPiece = { x, y };
        }
      }
    }
  }

  isInPlayerArea(x, y, playerId) {
    if (playerId === '0') {
      return y >= 6;
    } else {
      return y <= 5;
    }
  }

  isValidSetupPosition(from, toX, toY) {
    if (!this.isInPlayerArea(toX, toY, this.currentPlayer)) {
      return false;
    }

    const fromKey = `${from.x},${from.y}`;
    const piece = this.board[fromKey];

    if (!piece) return false;

    if (piece.type === '军旗') {
      return this.baseCamps[this.currentPlayer].some(pos => pos[0] === toX && pos[1] === toY);
    }

    if (piece.type === '地雷') {
      return !this.baseCamps[this.currentPlayer].some(pos => pos[0] === toX && pos[1] === toY);
    }

    return true;
  }

  movePieceInSetup(from, toX, toY) {
    const fromKey = `${from.x},${from.y}`;
    const toKey = `${toX},${toY}`;
    const piece = this.board[fromKey];
    const targetPiece = this.board[toKey];

    if (targetPiece && targetPiece.colorId === this.currentPlayer) {
      this.board[toKey] = piece;
      this.board[fromKey] = targetPiece;
    } else {
      this.board[toKey] = piece;
      this.board[fromKey] = null;
    }
  }

  completeSetup() {
    this.setupComplete[this.currentPlayer] = true;

    const flagInBaseCamp = this.baseCamps[this.currentPlayer].some(pos => {
      const key = `${pos[0]},${pos[1]}`;
      const piece = this.board[key];
      return piece && piece.type === '军旗';
    });

    if (!flagInBaseCamp) {
      this.showMessage('布阵失败：军旗必须放在大本营！');
      this.setupComplete[this.currentPlayer] = false;
      return;
    }

    this.showMessage(`${this.currentPlayer === '0' ? '红方' : '黑方'}布阵完成！`);

    if (!this.setupComplete['0'] || !this.setupComplete['1']) {
      this.currentPlayer = this.currentPlayer === '0' ? '1' : '0';
    } else {
      this.startBattlePhase();
    }
  }

  startBattlePhase() {
    this.gamePhase = 'battle';
    this.currentPlayer = '0';
    this.showMessage('对战开始！所有棋子已揭示！');

    Object.entries(this.board).forEach(([key, piece]) => {
      if (piece) {
        piece.revealed = true;
      }
    });
  }

  autoBattle(from, toX, toY) {
    const fromKey = `${from.x},${from.y}`;
    const toKey = `${toX},${toY}`;
    const attacker = this.board[fromKey];
    const defender = this.board[toKey];

    const result = this.battle(attacker, defender);

    if (result === 'win') {
      this.board[toKey] = attacker;
      this.board[toKey].revealed = true;
      delete this.board[fromKey];

      if (defender.type === '军旗') {
        this.endGame(attacker.colorId);
      } else {
        this.showMessage(`${attacker.type} 击败了 ${defender.type}！`);
      }
    } else if (result === 'lose') {
      delete this.board[fromKey];
      this.showMessage(`${defender.type} 击败了 ${attacker.type}！`);
    } else {
      delete this.board[fromKey];
      delete this.board[toKey];
      this.showMessage(`${attacker.type} 与 ${defender.type} 同归于尽！`);
    }
  }

  canMove(piece) {
    return piece.type !== '地雷' && piece.type !== '军旗';
  }

  isValidMove(from, toX, toY) {
    const fromKey = `${from.x},${from.y}`;
    const toKey = `${toX},${toY}`;
    const piece = this.board[fromKey];
    const targetPiece = this.board[toKey];

    if (targetPiece && targetPiece.colorId === piece.colorId) {
      return false;
    }

    const isCircle = this.list_circle.some(pos => pos[0] === from.x && pos[1] === from.y);
    const targetIsCircle = this.list_circle.some(pos => pos[0] === toX && pos[1] === toY);

    if (isCircle || targetIsCircle) {
      return this.isAdjacent(from.x, from.y, toX, toY);
    } else {
      return this.isValidNormalMove(from.x, from.y, toX, toY);
    }
  }

  isAdjacent(fromX, fromY, toX, toY) {
    const dx = Math.abs(toX - fromX);
    const dy = Math.abs(toY - fromY);
    return (dx === 1 && dy === 0) || (dx === 0 && dy === 1);
  }

  isValidNormalMove(fromX, fromY, toX, toY) {
    const dx = Math.abs(toX - fromX);
    const dy = Math.abs(toY - fromY);

    if ((dx === 1 && dy === 0) || (dx === 0 && dy === 1)) {
      return true;
    }

    return this.canFastMove(fromX, fromY, toX, toY);
  }

  canFastMove(fromX, fromY, toX, toY) {
    const fromIsFast = this.list_fast.some(pos => pos[0] === fromX && pos[1] === fromY);
    const toIsFast = this.list_fast.some(pos => pos[0] === toX && pos[1] === toY);

    if (!fromIsFast || !toIsFast) {
      return false;
    }

    return this.fastMovePath([fromX, fromY], [toX, toY], []);
  }

  fastMovePath(from, to, visited) {
    if (from[0] === to[0] && from[1] === to[1]) {
      return true;
    }

    const fromKey = from.join(',');
    if (visited.includes(fromKey)) {
      return false;
    }
    visited.push(fromKey);

    const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
    for (const [dx, dy] of directions) {
      const nextPos = [from[0] + dx, from[1] + dy];
      const nextKey = nextPos.join(',');

      if (this.list_fast.some(pos => pos[0] === nextPos[0] && pos[1] === nextPos[1])) {
        const nextPiece = this.board[nextKey];
        if (!nextPiece || (nextPos[0] === to[0] && nextPos[1] === to[1])) {
          if (this.fastMovePath(nextPos, to, [...visited])) {
            return true;
          }
        }
      }
    }

    return false;
  }

  movePiece(from, toX, toY) {
    const fromKey = `${from.x},${from.y}`;
    const toKey = `${toX},${toY}`;
    const piece = this.board[fromKey];
    const targetPiece = this.board[toKey];

    if (targetPiece) {
      const result = this.battle(piece, targetPiece);

      if (result === 'win') {
        this.board[toKey] = piece;
        delete this.board[fromKey];
        this.board[toKey].revealed = true;

        if (targetPiece.type === '军旗') {
          this.endGame(piece.colorId);
        }
      } else if (result === 'lose') {
        delete this.board[fromKey];
      } else {
        delete this.board[fromKey];
        delete this.board[toKey];
      }
    } else {
      this.board[toKey] = piece;
      delete this.board[fromKey];
    }
  }

  battle(attacker, defender) {
    if (attacker.type === '炸弹' || defender.type === '炸弹') {
      return 'draw';
    }

    if (attacker.type === '工兵' && defender.type === '地雷') {
      return 'win';
    }

    if (defender.type === '地雷') {
      return 'lose';
    }

    if (defender.type === '军旗') {
      return 'win';
    }

    if (attacker.rank > defender.rank) {
      return 'win';
    } else if (attacker.rank < defender.rank) {
      return 'lose';
    } else {
      return 'draw';
    }
  }

  switchTurn() {
    this.currentPlayer = this.currentPlayer === '0' ? '1' : '0';
  }

  endGame(winner) {
    this.gameOver = true;
    const winnerText = winner === '0' ? '红方' : '黑方';
    this.showMessage(`${winnerText}获胜！`);
  }

  showMessage(text) {
    // 微信小游戏使用console或简单的UI显示
    console.log(text);
    this.messageText = text;
    this.messageTimer = 120; // 显示2秒（60fps * 2）
  }

  restart() {
    this.currentPlayer = '0';
    this.selectedPiece = null;
    this.gameOver = false;
    this.gamePhase = 'setup';
    this.setupComplete = { '0': false, '1': false };
    this.initBoard();
    this.showMessage('游戏重新开始！');
  }

  render() {
    // 清空画布
    this.ctx.fillStyle = '#7f7f7f';
    this.ctx.fillRect(0, 0, this.screenWidth, this.screenHeight);

    // 绘制屏幕中心线（调试用）
    if (false) { // 设为true可以看到屏幕中心线
      this.ctx.strokeStyle = '#ff0000';
      this.ctx.lineWidth = 1;
      this.ctx.beginPath();
      this.ctx.moveTo(this.screenWidth / 2, 0);
      this.ctx.lineTo(this.screenWidth / 2, this.screenHeight);
      this.ctx.stroke();

      this.ctx.beginPath();
      this.ctx.moveTo(0, this.screenHeight / 2);
      this.ctx.lineTo(this.screenWidth, this.screenHeight / 2);
      this.ctx.stroke();
    }

    // 绘制棋盘边框（调试用）
    if (false) { // 设为true可以看到棋盘边界
      this.ctx.strokeStyle = '#00ff00';
      this.ctx.lineWidth = 2;
      this.ctx.strokeRect(this.offsetX, this.offsetY, this.gameWidth, this.gameHeight);
    }

    // 保存当前状态
    this.ctx.save();

    // 应用缩放和偏移
    this.ctx.translate(this.offsetX, this.offsetY);
    this.ctx.scale(this.scale, this.scale);

    // 绘制棋盘
    this.drawBoard();

    // 绘制棋子
    this.drawPieces();

    // 绘制大本营标记
    this.drawBaseCamps();

    // 绘制选中的棋子标记
    if (this.selectedPiece) {
      this.drawSelection();
      if (this.gamePhase === 'battle') {
        this.drawPossibleMoves();
      }
    }

    // 恢复状态
    this.ctx.restore();

    // 绘制游戏信息（不需要缩放，直接使用屏幕坐标）
    this.drawGameInfo();

    // 绘制消息
    if (this.messageTimer > 0) {
      this.drawMessage();
      this.messageTimer--;
    }
  }

  drawBoard() {
    // 绘制棋盘背景
    this.ctx.strokeStyle = '#0000ff';
    this.ctx.lineWidth = Math.max(1, 2 * this.scale);

    // 绘制格子
    for (let x = 0; x < this.boardWidth; x++) {
      for (let y = 0; y < this.boardHeight; y++) {
        if (this.list_circle.some(pos => pos[0] === x && pos[1] === y)) {
          // 绘制圆形位置
          const pos = this.toCanvas(x, y, true);
          const radius = this.cellWidth * 0.25; // 半径为格子宽度的25%
          this.ctx.beginPath();
          this.ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
          this.ctx.stroke();
        } else if (this.list_block.some(pos => pos[0] === x && pos[1] === y)) {
          // 绘制普通位置
          const pos = this.toCanvas(x, y, false);
          this.ctx.strokeRect(pos.x, pos.y, this.cellWidth, this.cellHeight);
        }
      }
    }

    // 绘制连接线
    this.drawRailwayLines();
  }

  drawRailwayLines() {
    // 自适应铁路线绘制
    const lineSpacing = Math.max(1, 2 * this.scale);

    // 绘制横线
    for (let y = 0; y < this.boardHeight; y++) {
      const yPos = this.offsetY + y * this.cellHeight + this.cellHeight / 2;
      this.ctx.beginPath();
      this.ctx.moveTo(this.offsetX + this.cellWidth / 2, yPos);
      this.ctx.lineTo(this.offsetX + this.gameWidth - this.cellWidth / 2, yPos);
      this.ctx.stroke();
    }

    // 绘制竖线
    for (let x = 0; x < this.boardWidth; x++) {
      const xPos = this.offsetX + x * this.cellWidth + this.cellWidth / 2;

      if (x === 1 || x === 3) {
        // 第1列和第3列的特殊绘制（避开中间区域）
        const midY = this.offsetY + this.gameHeight / 2;
        this.ctx.beginPath();
        this.ctx.moveTo(xPos, this.offsetY + this.cellHeight / 2);
        this.ctx.lineTo(xPos, midY - this.cellHeight / 2);
        this.ctx.stroke();

        this.ctx.beginPath();
        this.ctx.moveTo(xPos, midY + this.cellHeight / 2);
        this.ctx.lineTo(xPos, this.offsetY + this.gameHeight - this.cellHeight / 2);
        this.ctx.stroke();
      } else {
        // 其他列
        this.ctx.beginPath();
        this.ctx.moveTo(xPos, this.offsetY + this.cellHeight / 2);
        this.ctx.lineTo(xPos, this.offsetY + this.gameHeight - this.cellHeight / 2);
        this.ctx.stroke();
      }
    }

    // 绘制对角线（上半部分）
    this.drawDiagonalLines(true);

    // 绘制对角线（下半部分）
    this.drawDiagonalLines(false);
  }

  drawDiagonalLines(isTop) {
    const startY = isTop ? this.offsetY + this.cellHeight : this.offsetY + this.gameHeight / 2;
    const endY = isTop ? this.offsetY + this.gameHeight / 2 : this.offsetY + this.gameHeight - this.cellHeight;

    // 左上到右下对角线
    this.ctx.beginPath();
    this.ctx.moveTo(this.offsetX + this.cellWidth / 2, startY + this.cellHeight);
    this.ctx.lineTo(this.offsetX + this.gameWidth - this.cellWidth / 2, endY - this.cellHeight);
    this.ctx.stroke();

    // 右上到左下对角线
    this.ctx.beginPath();
    this.ctx.moveTo(this.offsetX + this.gameWidth - this.cellWidth / 2, startY + this.cellHeight);
    this.ctx.lineTo(this.offsetX + this.cellWidth / 2, endY - this.cellHeight);
    this.ctx.stroke();

    // 绘制菱形连接线
    const centerX = this.offsetX + this.gameWidth / 2;
    const center1Y = startY + this.cellHeight * 2;
    const center2Y = endY - this.cellHeight * 2;

    this.ctx.beginPath();
    this.ctx.moveTo(centerX, center1Y);
    this.ctx.lineTo(this.offsetX + this.cellWidth / 2, (center1Y + center2Y) / 2);
    this.ctx.lineTo(centerX, center2Y);
    this.ctx.lineTo(this.offsetX + this.gameWidth - this.cellWidth / 2, (center1Y + center2Y) / 2);
    this.ctx.closePath();
    this.ctx.stroke();
  }

  drawLine(x1, y1, x2, y2) {
    this.ctx.beginPath();
    this.ctx.moveTo(x1, y1);
    this.ctx.lineTo(x2, y2);
    this.ctx.stroke();
  }

  drawPieces() {
    Object.entries(this.board).forEach(([key, piece]) => {
      if (piece) {
        const [x, y] = key.split(',').map(Number);
        this.drawPiece(x, y, piece);
      }
    });
  }

  drawPiece(x, y, piece) {
    // 新的颜色系统：红方为红色，黑方为黑色
    let textColor;
    if (piece.colorId === '0') {
        textColor = '#ff0000'; // 红方：红色
    } else {
        textColor = '#000000'; // 黑方：黑色
    }

    const isCircle = this.list_circle.some(pos => pos[0] === x && pos[1] === y);

    if (isCircle) {
        // 圆形棋子
        const pos = this.toCanvas(x, y, true);
        const radius = this.cellWidth * 0.35; // 半径为格子宽度的35%
        this.ctx.beginPath();
        this.ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);

        // 棋子背景
        if (piece.revealed) {
            this.ctx.fillStyle = '#ffffff';
            this.ctx.fill();
            this.ctx.strokeStyle = '#333333';
            this.ctx.lineWidth = Math.max(1, 2 * this.scale);
            this.ctx.stroke();

            // 绘制文字，使用棋子颜色（黑棋需要白色边框）
            const fontSize = Math.max(10, Math.floor(this.cellHeight * 0.25));
            this.ctx.font = `bold ${fontSize}px Arial`;
            this.ctx.textAlign = 'center';
            this.ctx.textBaseline = 'middle';

            if (piece.colorId === '1') {
                // 黑棋：先绘制白色边框，再填充黑色
                this.ctx.strokeStyle = '#ffffff';
                this.ctx.lineWidth = Math.max(1, 3 * this.scale);
                this.ctx.strokeText(piece.type, pos.x, pos.y);
                this.ctx.fillStyle = '#000000';
                this.ctx.fillText(piece.type, pos.x, pos.y);
            } else {
                // 红棋：直接绘制红色文字
                this.ctx.fillStyle = '#ff0000';
                this.ctx.fillText(piece.type, pos.x, pos.y);
            }
        } else {
            // 未翻开的棋子：黑色背景
            this.ctx.fillStyle = '#000000';
            this.ctx.fill();
            this.ctx.strokeStyle = '#333333';
            this.ctx.lineWidth = Math.max(1, 2 * this.scale);
            this.ctx.stroke();

            // 绘制问号
            this.ctx.fillStyle = '#ffffff';
            const fontSize = Math.max(12, Math.floor(this.cellHeight * 0.3));
            this.ctx.font = `${fontSize}px Arial`;
            this.ctx.textAlign = 'center';
            this.ctx.textBaseline = 'middle';
            this.ctx.fillText('?', pos.x, pos.y);
        }
    } else {
        // 方形棋子
        const pos = this.toCanvas(x, y, false);
        const margin = this.cellWidth * 0.1; // 边距为格子宽度的10%

        if (piece.revealed) {
            // 棋子背景
            this.ctx.fillStyle = '#ffffff';
            this.ctx.fillRect(pos.x + margin, pos.y + margin, this.cellWidth - margin * 2, this.cellHeight - margin * 2);

            // 绘制边框
            this.ctx.strokeStyle = '#333333';
            this.ctx.lineWidth = Math.max(1, 2 * this.scale);
            this.ctx.strokeRect(pos.x + margin, pos.y + margin, this.cellWidth - margin * 2, this.cellHeight - margin * 2);

            // 绘制文字，使用棋子颜色（黑棋需要白色边框）
            const fontSize = Math.max(10, Math.floor(this.cellHeight * 0.25));
            this.ctx.font = `bold ${fontSize}px Arial`;
            this.ctx.textAlign = 'center';
            this.ctx.textBaseline = 'middle';

            const textX = pos.x + this.cellWidth / 2;
            const textY = pos.y + this.cellHeight / 2;

            if (piece.colorId === '1') {
                // 黑棋：先绘制白色边框，再填充黑色
                this.ctx.strokeStyle = '#ffffff';
                this.ctx.lineWidth = Math.max(1, 3 * this.scale);
                this.ctx.strokeText(piece.type, textX, textY);
                this.ctx.fillStyle = '#000000';
                this.ctx.fillText(piece.type, textX, textY);
            } else {
                // 红棋：直接绘制红色文字
                this.ctx.fillStyle = '#ff0000';
                this.ctx.fillText(piece.type, textX, textY);
            }
        } else {
            // 未翻开的棋子：黑色背景
            this.ctx.fillStyle = '#000000';
            this.ctx.fillRect(pos.x + margin, pos.y + margin, this.cellWidth - margin * 2, this.cellHeight - margin * 2);

            // 绘制边框
            this.ctx.strokeStyle = '#333333';
            this.ctx.lineWidth = Math.max(1, 2 * this.scale);
            this.ctx.strokeRect(pos.x + margin, pos.y + margin, this.cellWidth - margin * 2, this.cellHeight - margin * 2);

            // 绘制问号
            this.ctx.fillStyle = '#ffffff';
            const fontSize = Math.max(10, Math.floor(this.cellHeight * 0.3));
            this.ctx.font = `bold ${fontSize}px Arial`;
            this.ctx.textAlign = 'center';
            this.ctx.textBaseline = 'middle';

            const textX = pos.x + this.cellWidth / 2;
            const textY = pos.y + this.cellHeight / 2;
            this.ctx.fillText('?', textX, textY);
        }
    }
  }

  drawBaseCamps() {
    // 绘制大本营标记
    this.ctx.strokeStyle = '#ff00ff';
    this.ctx.lineWidth = Math.max(2, 4 * this.scale);

    Object.entries(this.baseCamps).forEach(([playerId, positions]) => {
        positions.forEach(([x, y]) => {
            const isCircle = this.list_circle.some(pos => pos[0] === x && pos[1] === y);
            const pos = this.toCanvas(x, y, isCircle);

            this.ctx.save();
            this.ctx.strokeStyle = playerId === this.currentPlayer ? '#ff00ff' : '#ff00ff40';

            if (isCircle) {
                // 圆形大本营
                this.ctx.beginPath();
                this.ctx.arc(pos.x, pos.y, this.cellWidth * 0.4, 0, Math.PI * 2);
                this.ctx.stroke();
            } else {
                // 方形大本营
                const margin = this.cellWidth * 0.08;
                this.ctx.strokeRect(
                    pos.x - margin,
                    pos.y - margin,
                    this.cellWidth + margin * 2,
                    this.cellHeight + margin * 2
                );
            }

            this.ctx.restore();
        });
    });
  }

  drawSelection() {
    if (!this.selectedPiece) return;

    const x = this.selectedPiece.x;
    const y = this.selectedPiece.y;

    const isCircle = this.list_circle.some(pos => pos[0] === x && pos[1] === y);

    if (isCircle) {
      const pos = this.toCanvas(x, y, true);
      this.ctx.strokeStyle = '#ffff00';
      this.ctx.lineWidth = Math.max(2, 5 * this.scale);
      this.ctx.beginPath();
      this.ctx.arc(pos.x, pos.y, this.cellWidth * 0.4, 0, Math.PI * 2);
      this.ctx.stroke();
    } else {
      const pos = this.toCanvas(x, y, false);
      this.ctx.strokeStyle = '#ffff00';
      this.ctx.lineWidth = Math.max(2, 5 * this.scale);
      this.ctx.strokeRect(pos.x, pos.y, this.cellWidth, this.cellHeight);
    }
  }

  drawPossibleMoves() {
    if (!this.selectedPiece) return;

    const from = this.selectedPiece;

    for (let x = 0; x < this.boardWidth; x++) {
      for (let y = 0; y < this.boardHeight; y++) {
        if (this.isValidMove(from, x, y)) {
          let pos;
          if (this.list_circle.some(pos => pos[0] === x && pos[1] === y)) {
            pos = this.toCanvas(x, y, true);
          } else {
            pos = this.toCanvas(x, y, false);
            pos.x += this.cellWidth / 2;
            pos.y += this.cellHeight / 2;
          }

          const key = `${x},${y}`;
          const targetPiece = this.board[key];

          this.ctx.beginPath();
          this.ctx.arc(pos.x, pos.y, this.cellWidth * 0.15, 0, Math.PI * 2);
          this.ctx.fillStyle = targetPiece ? '#ff0000' : '#00ff00';
          this.ctx.fill();
        }
      }
    }
  }

  drawGameInfo() {
    // 保存状态
    this.ctx.save();

    // 设置字体样式（自适应屏幕大小）
    const fontSize = Math.max(14, Math.floor(this.screenHeight * 0.03));
    this.ctx.font = `bold ${fontSize}px Arial`;
    this.ctx.textAlign = 'center';

    let phaseText = '';
    if (this.gamePhase === 'setup') {
      phaseText = `布阵阶段 - ${this.currentPlayer === '0' ? '红方' : '黑方'}排兵布阵`;
    } else {
      phaseText = '对战阶段';
    }

    // 在棋盘下方显示阶段信息
    const phaseY = this.uiTopY;
    this.ctx.fillStyle = '#ffffff';
    this.ctx.fillText(phaseText, this.screenWidth / 2, phaseY);

    // 显示当前玩家
    this.ctx.fillStyle = this.currentPlayer === '0' ? '#ff0000' : '#000000';
    const playerFontSize = Math.max(16, Math.floor(this.screenHeight * 0.035));
    this.ctx.font = `bold ${playerFontSize}px Arial`;
    const playerY = phaseY + fontSize + 10;
    this.ctx.fillText(this.currentPlayer === '0' ? '红方' : '黑方', this.screenWidth / 2, playerY);

    // 绘制按钮
    this.drawButtons();

    // 恢复状态
    this.ctx.restore();
  }

  drawButtons() {
    // 自适应按钮尺寸
    const buttonWidth = Math.max(100, this.gameWidth * 0.26);
    const buttonHeight = Math.max(40, this.screenHeight * 0.05);
    const buttonX = this.screenWidth / 2 - buttonWidth / 2;
    const buttonY = this.buttonY;

    // 完成布阵/重新开始按钮
    this.ctx.fillStyle = '#4CAF50';
    this.ctx.fillRect(buttonX, buttonY, buttonWidth, buttonHeight);
    this.ctx.strokeStyle = '#2E7D32';
    this.ctx.lineWidth = Math.max(1, 2 * this.scale);
    this.ctx.strokeRect(buttonX, buttonY, buttonWidth, buttonHeight);

    this.ctx.fillStyle = '#ffffff';
    const buttonFontSize = Math.max(14, Math.floor(buttonHeight * 0.4));
    this.ctx.font = `${buttonFontSize}px Arial`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    let buttonText = this.gamePhase === 'setup' ? '完成布阵' : '重新开始';
    const textX = buttonX + buttonWidth / 2;
    const textY = buttonY + buttonHeight / 2;
    this.ctx.fillText(buttonText, textX, textY);
  }

  drawMessage() {
    if (!this.messageText) return;

    // 自适应消息框尺寸
    const msgWidth = Math.max(200, this.gameWidth * 0.7);
    const msgHeight = Math.max(60, this.screenHeight * 0.15);
    const msgX = this.screenWidth / 2 - msgWidth / 2;
    const msgY = this.screenHeight / 2 - msgHeight / 2;

    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
    this.ctx.fillRect(msgX, msgY, msgWidth, msgHeight);

    this.ctx.fillStyle = '#ffffff';
    const msgFontSize = Math.max(16, Math.floor(msgHeight * 0.3));
    this.ctx.font = `bold ${msgFontSize}px Arial`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    const textX = msgX + msgWidth / 2;
    const textY = msgY + msgHeight / 2;
    this.ctx.fillText(this.messageText, textX, textY);
  }
}